#!/usr/bin/env bash
set -ex

cd $(dirname $0)/..

source ./scripts/version.sh

mkdir -p dist/artifacts

# We reorder the tar file so that the metadata files are at the start of the archive, which should make loading
# the runtime image faster. By default `docker image save` puts these at the end of the archive, which means the entire
# tarball needs to be read even if you're just loading a single image.
for FILE in build/images*.txt; do
    BASE=$(basename ${FILE} .txt)
    DEST=build/images/${PROG}-${BASE}.tar
    docker image save --output ${DEST}.tmp $(<${FILE})
    bsdtar -c -f ${DEST} --include=manifest.json --include=repositories @${DEST}.tmp
    bsdtar -r -f ${DEST} --exclude=manifest.json --exclude=repositories @${DEST}.tmp
    rm -f ${DEST}.tmp

    BASE=$(basename ${FILE} .txt)
    TARFILE=build/images/${PROG}-${BASE}.tar
    cp -f ${FILE} dist/artifacts/${PROG}-${BASE}.${PLATFORM}.txt
    zstd -T0 -16 -f --long=25 --no-progress ${TARFILE} -o dist/artifacts/${PROG}-${BASE}.${PLATFORM}.tar.zst
    pigz -v -c ${TARFILE} > dist/artifacts/${PROG}-${BASE}.${PLATFORM}.tar.gz
done

cat build/images*.txt | sort -V | uniq > dist/artifacts/${PROG}-images-all.${PLATFORM}.txt
